# -*- coding: utf-8 -*-
import json
import time
import requests
# from logger.log import other


class YDMHttp:
    apiurl = 'http://api.yundama.com/api.php'
    # username = 'lizhenjie'
    username = '17796665776'
    # password = '__xx00'
    password = 'mima954876314'
    appid = '5362'
    appkey = '92f80ac56199f7e7e480384c14fe65d2'

    def __init__(self, name, passwd, app_id, app_key):
        self.username = name
        self.password = passwd
        self.appid = str(app_id)
        self.appkey = app_key

    def request(self, fields, files=[]):
        response = self.post_url(self.apiurl, fields, files)
        response = json.loads(response)
        return response

    def balance(self):
        data = {
            'method': 'balance',
            'username': self.username,
            'password': self.password,
            'appid': self.appid,
            'appkey': self.appkey
        }
        response = self.request(data)
        if response:
            if response['ret'] and response['ret'] < 0:
                return response['ret']
            else:
                return response['balance']
        else:
            return -9001

    def login(self):
        data = {'method': 'login', 'username': self.username, 'password': self.password, 'appid': self.appid,
                'appkey': self.appkey}
        response = self.request(data)
        if response:
            if response['ret'] and response['ret'] < 0:
                return response['ret']
            else:
                return response['uid']
        else:
            return -9001

    def upload(self, filename, codetype, timeout):
        data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid,
                'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
        file = {'file': filename}
        response = self.request(data, file)
        if response:
            if response['ret'] and response['ret'] < 0:
                return response['ret']
            else:
                return response['cid']
        else:
            return -9001

    def result(self, cid):
        data = {'method': 'result', 'username': self.username, 'password': self.password, 'appid': self.appid,
                'appkey': self.appkey, 'cid': str(cid)}
        response = self.request(data)
        return response and response['text'] or ''

    def decode(self, file_name, code_type, time_out):
        cid = self.upload(file_name, code_type, time_out)
        if cid > 0:
            for i in range(0, time_out):
                result = self.result(cid)
                if result != '':
                    return cid, result
                else:
                    time.sleep(1)
            return -3003, ''
        else:
            return cid, ''

    def post_url(self, url, fields, files=[]):
        for key in files:
            files[key] = open(files[key], 'rb')
        res = requests.post(url, files=files, data=fields)
        return res.text

    def report_error(self, cid):
        data = {
            'method': 'report',
            'username': self.username,
            'password': self.password,
            'appid': self.appid,
            'appkey': self.appkey,
            'flag': 0,
            'cid': cid
        }

        response = self.request(data)
        if response:
            if response['ret']:
                return response['ret']
        else:
            return -9001


def code_verificate(name, passwd, file_name, code_type=1006, app_id=5362, app_key='92f80ac56199f7e7e480384c14fe65d2',
                    time_out=60):
    """
    http://www.yundama.com/ 登录页
        app_id, app_key 若在项目中使用  自行注册开发者账号
    :param name: 云打码注册用户名，这是普通用户注册，而非开发者用户注册名
    :param passwd: 用户密码
    :param file_name: 需要识别的图片名
    :param app_id: 软件ID
    :param app_key: 软件key
    :param code_type: 1005表示五位字符验证码。价格和验证码类别，详细请看http://www.yundama.com/price.html
    :param time_out: 超时时间
    :return: 验证码结果
    """
    yundama_obj = YDMHttp(name, passwd, app_id, app_key)
    yundama_obj.login()

    rest = yundama_obj.balance()
    print "剩余题分", rest
    if rest <= 0:
        raise Exception('云打码已经欠费了，请及时充值')
    if rest <= 100:
        print('云打码余额已不多，请注意及时充值')

    # 开始识别，图片路径，验证码类型ID，超时时间（秒），识别结果
    cid, result = yundama_obj.decode(file_name, code_type, time_out)

    # 如果验证码识别失败,递归
    if result == u"看不清":
        print "验证码识别失败,重新识别"
        result, yundama_obj, cid = code_verificate(name, passwd, file_name, code_type=1006)

    return result, yundama_obj, cid


headers = {
    "Host": "catalogue.bosch-trading.com.cn",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
    "Cookie": "UM_distinctid=1648d9f06cb150-0719ad59bd385b-16386952-13c680-1648d9f06cc225; ci_session=ufjq4nb1p4hv7avh2jm1072r8eqre12d; CNZZDATA1257733696=419851453-1531383363-%7C1532396560",
}


if __name__ == '__main__':
    # 云打码注册的登录用户名（通过用户注册）
    # username = 'lizhenjie'
    username = '17796665776'
    # 登录密码
    # password = '__xx00'
    password = 'mima954876314'

    verify_url = "https://catalogue.bosch-trading.com.cn/captcha/verification"

    response = requests.get(url=verify_url, headers=headers)
    with open('./code.png', 'wb') as f:
        f.write(response.content)


    # 文件名
    file_name = './code.png'
    rs = code_verificate(username, password, file_name, code_type=1006)
    print rs
    vlidateCode = rs[0]
    print(vlidateCode)